import React, { useState } from "react";
import { Card, Form, Input, Button, message, Select, Space, Modal } from "antd";
import type { EMRRecord, EMRTemplate, Prescription } from "../../types/emr";
import { useNavigate, useLocation } from "react-router-dom";
import Layout from "../../components/Layout";

const templates: EMRTemplate[] = [
  { id: 't1', name: '骨关节炎常用模板', fields: { chiefComplaint: '膝关节疼', diagnosis: '骨关节炎', prescription: [{ drugName:'氨糖', dosage:'0.75g', usage:'口服bid', days: 30 }] } },
  { id: 't2', name: '腰肌劳损模板', fields: { chiefComplaint: '腰痛', diagnosis: '腰肌劳损' } }
];

const EMREdit: React.FC = () => {
  const [form] = Form.useForm<EMRRecord>();
  const [templateModal, setTemplateModal] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  // 加载模板信息并自动填充表单
  const applyTemplate = (tpl: EMRTemplate) => {
    form.setFieldsValue(tpl.fields as any);
    setTemplateModal(false);
  };
  const handleFinish = (values: any) => {
    message.success('保存成功');
    setTimeout(() => navigate('/doctor/emr'), 800);
  };
  return (
    <Layout title="编辑/新增电子病历">
      <Card style={{maxWidth:780,margin:'0 auto'}}>
      <Space style={{marginBottom: 16}}>
        <Button onClick={()=>setTemplateModal(true)}>应用模板</Button>
      </Space>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleFinish}
        initialValues={{ prescription: [] }}
      >
        <Form.Item name="chiefComplaint" label="主诉" rules={[{ required:true, message:'请填写主诉' }]}> <Input /> </Form.Item>
        <Form.Item name="history" label="现病史" rules={[{ required:true, message:'请填写现病史' }]}> <Input.TextArea autoSize /> </Form.Item>
        <Form.Item name="physicalExam" label="体格检查" rules={[{ required:true, message:'请填写体格检查' }]}> <Input.TextArea autoSize /> </Form.Item>
        <Form.Item name="diagnosis" label="诊断" rules={[{ required:true, message:'请填写诊断' }]}> <Input /> </Form.Item>
        <Form.List name="prescription" rules={[{ validator: (_, prescs) => !prescs || prescs.length>0? Promise.resolve():Promise.reject('请至少填写一个药品') }]}>
          {(fields, { add, remove }, { errors } ) => (
            <>
              <label>处方</label>
              {fields.map((field,idx) => (
                <Space key={field.key} align="start">
                  <Form.Item {...field} name={[field.name, 'drugName']} rules={[{ required:true, message:'药品名必填'}]} noStyle>
                    <Input placeholder="药品名" style={{width:100}} />
                  </Form.Item>
                  <Form.Item {...field} name={[field.name, 'dosage']} rules={[{ required:true,message:'剂量必填'}, {pattern:/^\d+(\.\d+)?(mg|g|ml)$/i,message:'格式如0.1g'}]} noStyle>
                    <Input placeholder="剂量" style={{width:80}} />
                  </Form.Item>
                  <Form.Item {...field} name={[field.name, 'usage']} rules={[{ required:true}]} noStyle>
                    <Input placeholder="用法" style={{width:100}} />
                  </Form.Item>
                  <Form.Item {...field} name={[field.name, 'days']} rules={[{required:true, type:'number', min:1, message:'填写天数'}]} noStyle>
                    <Input type="number" placeholder="天数" style={{width:60}} />
                  </Form.Item>
                  <Button onClick={()=>remove(field.name)} danger size="small">删除</Button>
                </Space>
              ))}
              <Button onClick={()=>add()} style={{marginTop:8}}>添加药品</Button>
              <div style={{ color:'#ff4d4f' }}>{errors}</div>
            </>
          )}
        </Form.List>
        <Form.Item>
          <Button type="primary" htmlType="submit">保存</Button>
        </Form.Item>
      </Form>
      <Modal title="选择模板" open={templateModal} onCancel={()=>setTemplateModal(false)} footer={null}>
        {templates.map(tpl => (
          <Card key={tpl.id} size="small" style={{marginBottom:12}}>
            <div>{tpl.name}</div>
            <Button size="small" onClick={()=>applyTemplate(tpl)}>应用此模板</Button>
          </Card>
        ))}
      </Modal>
      </Card>
    </Layout>
  );
};
export default EMREdit;
